<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="程序员姓名" prop="programmerName">
        <el-input v-model="queryParams.programmerName" placeholder="请输入程序员姓名" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单任务类型" prop="orderTaskName">
        <el-select v-model="queryParams.orderTaskName" placeholder="请选择任务类型" clearable>
          <el-option v-for="task in taskTypeOptions" :key="task.value" :label="task.label" :value="task.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskState">
        <el-select v-model="queryParams.taskState" placeholder="请选择任务状态" clearable>
          <el-option v-for="item in taskStateOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="提现状态" prop="withdrawalStatus">
        <el-select v-model="queryParams.withdrawalStatus" placeholder="请选择提现状态" clearable>
          <el-option v-for="item in withdrawalStatusOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务接单状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择任务接单状态" clearable>
          <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="最终任务金额" prop="finalTaskAmount">
        <el-input v-model="queryParams.finalTaskAmount" placeholder="请输入最终任务金额" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dashboard:externalOrders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dashboard:externalOrders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dashboard:externalOrders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dashboard:externalOrders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="externalOrdersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="外部订单ID" align="center" prop="id" /> -->
      <!-- <el-table-column label="订单号" align="center" prop="gradOrdersId" /> -->
      <!-- <el-table-column label="订单任务ID" align="center" prop="gradOrdersTaskId" /> -->
      <!-- <el-table-column label="程序员ID" align="center" prop="programmerId" /> -->
      <!-- <el-table-column label="包单价" align="center" prop="biddingAmount" /> -->
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="订单标题" align="center" prop="orderTitle" />
      <el-table-column label="订单任务类型" align="center" prop="orderTaskName" />
      <el-table-column label="程序类型" align="center" prop="techType" />
      <el-table-column label="程序员姓名" align="center" prop="programmerName" />
      <el-table-column label="最终任务金额" align="center" prop="finalTaskAmount" />
      <el-table-column label="任务状态" align="center" prop="taskState">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(taskStateOptions, scope.row.taskState) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提现状态" align="center" prop="withdrawalStatus">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(withdrawalStatusOptions, scope.row.withdrawalStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务接单状态" align="center" prop="state">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(stateOptions, scope.row.state) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否加急" align="center" prop="isUrgent">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isUrgent === '1' ? 'danger' : 'info'" size="small">{{
            selectDictLabel(isUrgentOptions, scope.row.isUrgent) }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="需求介绍" align="center" prop="introduce" /> -->
      <el-table-column label="预计完成时间" align="center" prop="estimatedEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estimatedEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所需信用分" align="center" prop="requiredCreditScore" />
      <!-- <el-table-column label="所需技能等级ID" align="center" prop="requiredSkillLevelId" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-money"
            @click="handleWithdrawal(scope.row)"
            v-hasPermi="['dashboard:withdrawalApplication:add']"
            v-if="canApplyWithdrawal(scope.row)"
          >提现申请</el-button>
        <!--   <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dashboard:externalOrders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dashboard:externalOrders:remove']"
          >删除</el-button> -->
        </template> 
      </el-table-column> 
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改微信预抢订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="gradOrdersId">
          <el-input v-model="form.gradOrdersId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="订单任务ID" prop="gradOrdersTaskId">
          <el-input v-model="form.gradOrdersTaskId" placeholder="请输入订单任务ID" />
        </el-form-item>
        <el-form-item label="订单任务类型" prop="orderTaskName">
          <el-input v-model="form.orderTaskName" placeholder="请输入订单任务类型" />
        </el-form-item>
        <el-form-item label="程序员姓名" prop="programmerName">
          <el-input v-model="form.programmerName" placeholder="请输入程序员姓名" />
        </el-form-item>
        <el-form-item label="程序员ID" prop="programmerId">
          <el-input v-model="form.programmerId" placeholder="请输入程序员ID" />
        </el-form-item>
        <el-form-item label="包单价" prop="biddingAmount">
          <el-input v-model="form.biddingAmount" placeholder="请输入包单价" />
        </el-form-item>
        <el-form-item label="最终任务金额" prop="finalTaskAmount">
          <el-input v-model="form.finalTaskAmount" placeholder="请输入最终任务金额" />
        </el-form-item>
        <el-form-item label="状态 0=未中单,1=任务进行中,2=任务已完成,3=移交客户,4=任务结束,5=技术退单(扣除信用分),6=客户退单(补偿款)" prop="taskState">
          <el-input v-model="form.taskState"
            placeholder="请输入状态 0=未中单,1=任务进行中,2=任务已完成,3=移交客户,4=任务结束,5=技术退单(扣除信用分),6=客户退单(补偿款)" />
        </el-form-item>
        <el-form-item label="订单状态 0=未派单,1=未中单,2=中单" prop="state">
          <el-input v-model="form.state" placeholder="请输入订单状态 0=未派单,1=未中单,2=中单" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="订单标题" prop="orderTitle">
          <el-input v-model="form.orderTitle" placeholder="请输入订单标题" />
        </el-form-item>
        <el-form-item label="是否加急" prop="isUrgent">
          <el-input v-model="form.isUrgent" placeholder="请输入是否加急" />
        </el-form-item>
        <el-form-item label="需求介绍" prop="introduce">
          <el-input v-model="form.introduce" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="预计完成时间" prop="estimatedEndTime">
          <el-date-picker clearable v-model="form.estimatedEndTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择预计完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所需信用分" prop="requiredCreditScore">
          <el-input v-model="form.requiredCreditScore" placeholder="请输入所需信用分" />
        </el-form-item>
        <el-form-item label="所需技能等级ID" prop="requiredSkillLevelId">
          <el-input v-model="form.requiredSkillLevelId" placeholder="请输入所需技能等级ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExternalOrders, getExternalOrders, delExternalOrders, addExternalOrders, updateExternalOrders, addWithdrawalApplication } from "@/api/dashboard/externalOrders"
import { listType } from "@/api/dashboard/type"

export default {
  name: "ExternalOrders",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微信预抢订单表格数据
      externalOrdersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 任务类型选项
      taskTypeOptions: [],
      // 任务状态选项
      taskStateOptions: [
        { value: '0', label: '未中单' },
        { value: '1', label: '任务进行中' },
        { value: '2', label: '任务已完成' },
        { value: '3', label: '移交客户' },
        { value: '4', label: '任务结束' },
        { value: '5', label: '技术退单(扣除信用分)' },
        { value: '6', label: '客户退单(补偿款)' },
        { value: '7', label: '拒绝提现' }
      ],
      // 提现状态选项
      withdrawalStatusOptions: [
        { value: '0', label: '不可提现' },
        { value: '1', label: '提现首款可申请' },
        { value: '2', label: '已提现首款' },
        { value: '3', label: '尾款可申请' },
        { value: '4', label: '已提现尾款' },
        { value: '5', label: '首款提现失败' },
        { value: '6', label: '尾款提现失败' }
      ],
      // 任务接单状态
      stateOptions: [
        { value: '0', label: '未派单' },
        { value: '1', label: '未中单' },
        { value: '2', label: '中单' },
        { value: '3', label: '已退单' }
      ],
      // 是否加急
      isUrgentOptions: [
        { value: '0', label: '不加急' },
        { value: '1', label: '加急' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gradOrdersId: null,
        orderTaskName: null,
        programmerName: null,
        programmerId: null,
        biddingAmount: null,
        state: null,
        orderNo: null,
        taskState: null,
        withdrawalStatus: null,
        finalTaskAmount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
    this.getTaskTypes()
  },
  methods: {
    /** 查询微信预抢订单列表 */
    getList() {
      this.loading = true
      listExternalOrders(this.queryParams).then(response => {
        this.externalOrdersList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取任务类型 */
    getTaskTypes() {
      listType({ pageNum: 1, pageSize: 999 }).then(response => {
        this.taskTypeOptions = response.rows.map(item => ({
          value: item.orderTaskName,
          label: item.orderTaskName
        }))
      })
    },
    /** 转换字典标签 */
    selectDictLabel(datas, value) {
      if (value === undefined || value === null || value === '') {
        return "";
      }
      const actions = [];
      Object.keys(datas).map((key) => {
        if (datas[key].value == ('' + value)) {
          actions.push(datas[key].label);
          return false;
        }
      })
      return actions.join('');
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        gradOrdersId: null,
        gradOrdersTaskId: null,
        orderTaskName: null,
        programmerName: null,
        programmerId: null,
        biddingAmount: null,
        finalTaskAmount: null,
        withdrawalStatus: null,
        taskState: null,
        state: null,
        orderNo: null,
        orderTitle: null,
        isUrgent: null,
        introduce: null,
        techType: null,
        estimatedEndTime: null,
        requiredCreditScore: null,
        requiredSkillLevelId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加微信预抢订单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getExternalOrders(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改微信预抢订单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExternalOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addExternalOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除微信预抢订单编号为"' + ids + '"的数据项？').then(function () {
        return delExternalOrders(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dashboard/externalOrders/export', {
        ...this.queryParams
      }, `externalOrders_${new Date().getTime()}.xlsx`)
    },
    /** 判断是否可以申请提现 */
    canApplyWithdrawal(row) {
      // 条件1: taskState = 2 (任务已完成) 并且 withdrawalStatus = 1 (提现首款可申请)
      // 条件2: taskState = 3 (移交客户) 并且 withdrawalStatus = 3 (尾款可申请)
      return (row.taskState === '2' && row.withdrawalStatus === '1') || 
             (row.taskState === '3' && row.withdrawalStatus === '3')
    },
    /** 提现申请按钮操作 */
    handleWithdrawal(row) {
      // 根据不同的状态确定 withdrawalType
      let withdrawalType = 1 // 默认值
      let withdrawalTypeName = "首款提现"
      
      if (row.taskState === '2' && row.withdrawalStatus === '1') {
        // 任务已完成，提现首款可申请
        withdrawalType = 1
        withdrawalTypeName = "首款提现"
      } else if (row.taskState === '3' && row.withdrawalStatus === '3') {
        // 移交客户，尾款可申请
        withdrawalType = 2
        withdrawalTypeName = "尾款提现"
      }
      
      // 构建提现申请参数
      const withdrawalData = {
        gradOrdersId: row.gradOrdersId,
        gradOrdersTaskId: row.gradOrdersTaskId,
        orderTaskTypeName: row.orderTaskName,
        applicationAmount: row.finalTaskAmount,
        withdrawalType: withdrawalType
      }
      
      this.$modal.confirm(`确认申请${withdrawalTypeName}订单"${row.orderNo}"的金额 ¥${row.finalTaskAmount} 吗？`).then(() => {
        addWithdrawalApplication(withdrawalData).then(response => {
          this.$modal.msgSuccess(`${withdrawalTypeName}申请提交成功`)
          this.getList() // 刷新列表
        }).catch(error => {
          this.$modal.msgError(`${withdrawalTypeName}申请失败：` + (error.message || "未知错误"))
        })
      }).catch(() => {
        this.$modal.msgInfo(`已取消${withdrawalTypeName}申请`)
      })
    }
  }
}
</script>
